package com.erji.common.mybatis.meta;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.erji.common.domain.CommConstants;
import com.erji.common.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {
    private static final String CREATE_DATE = "createDate";
    private static final String CREATE_BY = "createBy";
    private static final String CREATE_BY_NAME = "createByName";
    private static final String UPDATE_DATE = "updateDate";
    private static final String UPDATE_BY_NAME = "updateByName";
    private static final String UPDATE_BY = "updateBy";
    private static final String DELETE_FLAG = "deleteFlag";

    public MybatisMetaObjectHandler() {
    }

    public void insertFill(MetaObject metaObject) {
        Date now = new Date();

        this.fillStrategy(metaObject, "createDate", now);
        this.fillStrategy(metaObject, "createBy", SecurityUtils.getUserId());

//        Object createByName = this.getFieldValByName("createByName", metaObject);
//        if (ObjectUtils.isEmpty(createByName)) {
//            this.strictInsertFill(metaObject, "createByName", String.class, SecurityUtils.getUsername());
//        }
        this.fillStrategy(metaObject, "deleteFlag", CommConstants.DEL_FLAG_NORMAL);

        this.updateCustomModifiedFields(metaObject);
    }

    public void updateFill(MetaObject metaObject) {
        this.updateCustomModifiedFields(metaObject);
    }

    private void updateCustomModifiedFields(MetaObject metaObject) {
        Date now = new Date();
        Object updateDate = this.getFieldValByName("updateDate", metaObject);
        if (ObjectUtils.isEmpty(updateDate)) {
            this.strictUpdateFill(metaObject, "updateDate", Date.class, now);
        }

        Object updateBy = this.getFieldValByName("updateBy", metaObject);
        if (ObjectUtils.isEmpty(updateBy)) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, SecurityUtils.getUserId());
        }

//        Object updateByName = this.getFieldValByName("updateByName", metaObject);
//        if (ObjectUtils.isEmpty(updateByName)) {
//            this.strictInsertFill(metaObject, "updateByName", String.class, SecurityUtils.getUsername());
//        }

    }
}
